package com.bjb.vr.common.service;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.bjb.vr.common.constant.Constants;
import com.bjb.vr.common.exception.CommonException;
import com.bjb.vr.common.utils.LocalFileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 本地文件操作服务
 *
 * @version 1.0.0
 * @author: HuJingBo
 * @time: 2022/4/14 11:30
 */
@Slf4j
@RefreshScope
@Service
@Configuration
@ConditionalOnProperty(prefix = "spring.file.upload.service", name = "selection", havingValue = "local")
public class LocalOperationService implements FileOperationService {

    @Value("${local.file.view.path:/local/static/}")
    private String fileViewPath;

    @Value("${local.file.upload.path:/data/resource/upload/}")
    private String fileUploadPath;

    @Value("${local.file.upload.host:127.0.0.1}")
    private String fileUploadHost;

    @Autowired
    private Environment environment;

    @Autowired
    private NacosDiscoveryProperties discoveryProperties;


    @Override
    public String uploadFile(MultipartFile file) {
        try {
            log.info("开始上传文件：{}", file.getOriginalFilename());
            LocalFileUtil.uploadFile(file, fileUploadPath);
            log.info("上传文件成功：{}", file.getOriginalFilename());
        } catch (IOException e) {
            throw new CommonException(e.getMessage());
        }
        String ip = discoveryProperties.getIp();
        String port = environment.getProperty("server.port");
        log.info("fileUploadHost：{}",fileUploadHost);
        return Constants.HTTP + fileUploadHost + ":" + port + fileViewPath + file.getOriginalFilename();
    }

    @Override
    public String downloadFile(String fileName) {
        String ip = discoveryProperties.getIp();
        String port = environment.getProperty("server.port");
        String viewPath = fileViewPath.split("\\*")[0];
        return Constants.HTTP + fileUploadHost + ":" + port + viewPath + fileName;
    }

    @Override
    public byte[] downloadFileBytes(String fileName) {
        return new byte[0];
    }
}
